package controllers.home;

import hprose.HproseClinetService;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.type.descriptor.java.DataHelper;

import play.Logger;
import play.cache.Cache;
import utils.convert.Convert;
import utils.date.DateUtils;
import utils.file.DownExcel;
import utils.https.HttpRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ning.http.util.DateUtil;

import component.UserBis;
import constants.APIConstants;
import constants.Constants;
import controllers.common.filter.BaseFilter;
import controllers.login.LoginAction;
import controllers.useRecord.UseRecordAction;

public class HomeAction extends BaseFilter {

	public static void index(){
		String res = "";
		String  estimate_start_date = params.get("estimate_start_date");
		String  estimate_end_date = params.get("estimate_end_date");
		String  estimate_project_id = params.get("estimate_project_id");
		String  estimate_supplier_id = params.get("estimate_supplier_id");
		String  estimate_material_id = params.get("estimate_material_id");
		Map<String, Object> useNumParam = new HashMap<String, Object>();
		Object[] arguments = new Object[] { useNumParam };
		useNumParam.put("customer_id", UserBis.currUser());
		useNumParam.put("date", DateUtils.getCurrentDateTimeSimple());
		useNumParam.put("isPage", Constants.DATAISPAGE_NO);
		useNumParam.put("states", "0,1,2,4");
		res = HproseClinetService.synCall(APIConstants.SMSI_HOMESTATISTICSLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject projects = JSONObject.parseObject(HproseClinetService.synCall(APIConstants.PJMSI_GETPROJECT, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		String cutterspesc = HproseClinetService.synCall(APIConstants.CSMI_GETCUTTERSPECS, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String operatorRes = HproseClinetService.synCall(APIConstants.OMSI_GETOPERATOR, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String supplierstr = "";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("start", "1");
		map.put("length", "1000");
		try {
			 supplierstr = HttpRequest.getInstance().doGet(APIConstants.SUPPLIER_LIST+UserBis.currUser(), map);
		} catch (Exception e) {
			Logger.info(e.getMessage());
		}
		useNumParam.put("inv_material_id", params.get("inv_material_id"));
		useNumParam.put("isAll", params.get("isAll"));
		JSONObject invObj = JSONObject.parseObject(HproseClinetService.synCall(APIConstants.TIMSI_GETSAFEINVENTORYLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		JSONObject operators = JSONObject.parseObject(operatorRes);
		useNumParam.put("isPage", Constants.DATAISPAGE_YES);
		useNumParam.put("currPage", params.get("currPage"));
		useNumParam.put("pageSize", params.get("pageSize"));
		useNumParam.put("project_id", params.get("project_id"));
		useNumParam.put("operator_id", params.get("operator_id"));
		useNumParam.put("material_id", params.get("material_id"));
		useNumParam.put("start_date", params.get("start_date"));
		useNumParam.put("end_date", params.get("end_date"));
		useNumParam.put("type", params.get("type"));
		useNumParam.put("supplier_id", params.get("supplier_id"));
		useNumParam.put("rec_desc", params.get("rec_desc"));
		if(StringUtils.isNotBlank(params.get("start_date"))||StringUtils.isNotBlank(params.get("end_date"))){
			useNumParam.remove("date");
		}else{
			useNumParam.put("date", DateUtils.getCurrentDateTimeSimple());
		}
		JSONObject useCutters = JSONObject.parseObject( HproseClinetService.synCall(APIConstants.URMI_GETCUTTERDETAILBYOPERATORID, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("customer_id", UserBis.currUser());
		map2.put("start_date",estimate_start_date);
		map2.put("end_date", estimate_end_date);
		map2.put("project_id",estimate_project_id);
		map2.put("material_id", estimate_material_id);
		map2.put("supplier_id", estimate_supplier_id);
		Object[] arguments2 = new Object[] { map2 };
		JSONObject cutterEstimateObj = JSONObject.parseObject( HproseClinetService.synCall(APIConstants.SMSI_CUTTERINVENTORYANDYIELDESTIMATE, arguments2,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		Logger.info("cutterspecs-->"+cutterspesc);
		String useNum = "0";
		String useCount = "0";
		String recNum = "0";
		String recCount = "0";
		String cutterLifeSUM = "0";
		String cutterLifeAVG = "0";

		if("服务不可用".equals(res)||"服务不可用".equals(cutterspesc)){
			renderArgs.put("error", "-1");
			LoginAction.login();
		} 
		JSONObject useCutterObj = useCutters.getJSONObject("data");

 		JSONObject custCutters = JSONObject.parseObject(cutterspesc);
		JSONObject jsonStr = JSONObject.parseObject(res);
		JSONObject suppliers = JSONObject.parseObject(supplierstr).getJSONObject("data");
		JSONArray arr = jsonStr.getJSONArray("data");
		useNum = arr.getJSONObject(0).get("useNum")+"";
		useCount = arr.getJSONObject(0).get("useCount")+"";
		recNum = arr.getJSONObject(0).get("recNum")+"";
		DecimalFormat   df   =new   DecimalFormat("#.00");  
		cutterLifeSUM = arr.getJSONObject(0).get("cutterLifeSUM")+"";
		cutterLifeAVG = df.format(Convert.convertToDouble(arr.getJSONObject(0).get("cutterLifeAVG")+"",0));

		String inv_material_id =  params.get("inv_material_id");
		String isAll =  params.get("isAll");

		render(useNum, useCount,recNum,recCount,custCutters,useCutterObj,projects,operators,invObj,inv_material_id,isAll,suppliers,cutterLifeAVG,cutterLifeSUM,
				estimate_start_date,estimate_end_date,estimate_project_id,estimate_material_id,
				estimate_supplier_id
				,cutterEstimateObj
				);
		
	}
	public static void home() {
		String res = "";
		if ("2".equals(UserBis.currType())) {
			Map<String, Object> useNumParam = new HashMap<String, Object>();
			Object[] arguments = new Object[] { useNumParam };
			useNumParam.put("customer_id", UserBis.currUser());
			useNumParam.put("date", DateUtils.getCurrentDateTimeSimple());
			res = HproseClinetService.synCall(APIConstants.SMSI_HOMESTATISTICSLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
			useNumParam.put("isPage", Constants.DATAISPAGE_NO);
			String cutterspesc = HproseClinetService.synCall(APIConstants.CSMI_GETCUTTERSPECS, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
			Logger.info("cutterspecs-->"+cutterspesc);
			String useNum = "0";
			String useCount = "0";
			String recNum = "0";
			String recCount = "0";
			if("服务不可用".equals(res)||"服务不可用".equals(cutterspesc)){
				renderArgs.put("error", "-1");
				LoginAction.login();
			}
			JSONObject custCutters = JSONObject.parseObject(cutterspesc);
			JSONObject custCutterSupps = JSONObject.parseObject(HproseClinetService.synCall(APIConstants.CSMI_GETCUTTERSPECSANDSUPPNAME, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
			JSONObject jsonStr = JSONObject.parseObject(res);
			JSONArray arr = jsonStr.getJSONArray("data");
			useNum = arr.getJSONObject(0).get("useNum")+"";
			useCount = arr.getJSONObject(0).get("useCount")+"";
			recNum = arr.getJSONObject(0).get("recNum")+"";
			recCount = arr.getJSONObject(0).get("recCount")+"";
			render(useNum, useCount,recNum,recCount,custCutters,custCutterSupps);
		} else if ("3".equals(UserBis.currType())) {
			UseRecordAction.index();
		}
	}
	/**
	 * 获取项目所使用的刀具
	 */
	public static void getProjectCutter(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id", UserBis.currUser());
		map.put("project_id", params.get("project_id"));
		String res = HproseClinetService.synCall(APIConstants.CSMI_GETCUTTERSPECSBYPROJECTID, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	
	/**
	 * 获取刀具库存详情
	 */
	public static void getInventoryDetail(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id", UserBis.currUser());
		map.put("material_id", params.get("material_id"));
		map.put("terminal_id", params.get("terminal_id"));
		String res = HproseClinetService.synCall(APIConstants.TIMSI_GETINVENTORYBYCUSTOMERIDANDMATERIELID, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	
	public static void downUseCutter(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[]{map};
		map.put("isPage", Constants.DATAISPAGE_NO);
		map.put("customer_id", UserBis.currUser());
		map.put("project_id", params.get("project_id"));
		map.put("operator_id", params.get("operator_id"));
		map.put("material_id", params.get("material_id"));
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		map.put("type", params.get("type"));
		JSONObject useCutters = JSONObject.parseObject( HproseClinetService.synCall(APIConstants.URMI_GETCUTTERDETAILBYOPERATORID, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		if(useCutters.getString("ret").equals("1000")){
			JSONObject useCutter = useCutters.getJSONObject("data");
		List<Map<String,Object>> list = (List<Map<String,Object>>)useCutter.get("data");
		HSSFWorkbook wb = DownExcel.downExcel("领用回收记录", "物料编码:规格简称:规格全称:供应商:操作人:数量:操作类型:操作时间:操作原因:寿命", 
        		"customer_specs_no:simple_specs_cust:long_specs_cust:supp_name:real_name:num:type:time:rec_desc:cutter_life", list);
        // 生成文件名
        String fileName = "UseCutterDetails" + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + ".xls";
        try {
            response.setContentTypeIfNotSet("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "GB2312"));
            OutputStream out = response.out;
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            list.clear();
        }
		}
	}
	
	public static void downInventoryDetail(){
		Map<String, Object> map = new HashMap<String, Object>();
			Object[] arguments = new Object[]{map};
		map.put("isPage", Constants.DATAISPAGE_NO);
		map.put("customer_id", UserBis.currUser());
		map.put("inv_material_id", params.get("inv_material_id"));
		map.put("isAll", params.get("isAll"));
		JSONObject invObj = JSONObject.parseObject(HproseClinetService.synCall(APIConstants.TIMSI_GETSAFEINVENTORYLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		List<Map<String,Object>> list = (List<Map<String,Object>>)invObj.get("data");
        HSSFWorkbook wb = DownExcel.downExcel("实时库存", "物料编码:规格简称:规格全称:供应商:当前库存:安全库存:操作时间", 
        		"customer_specs_no:simple_specs_cust:long_specs_cust:supp_name:now_num:safe_num:date", list);
        // 生成文件名
        String fileName = "InventoryDetails" + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") +	 ".xls";
        try {
            response.setContentTypeIfNotSet("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "GB2312"));
            OutputStream out = response.out;
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            list.clear();
        }
	}
	public static void downEstimate(){
		Map<String, Object> map2 = new HashMap<String, Object>();
		String  estimate_start_date = params.get("estimate_start_date");
		String  estimate_end_date = params.get("estimate_end_date");
		String  estimate_project_id = params.get("estimate_project_id");
		String  estimate_supplier_id = params.get("estimate_supplier_id");
		String  estimate_material_id = params.get("estimate_material_id");
		map2.put("customer_id", UserBis.currUser());
		map2.put("start_date",estimate_start_date);
		map2.put("end_date", estimate_end_date);
		map2.put("project_id",estimate_project_id);
		map2.put("material_id", estimate_material_id);
		map2.put("supplier_id", estimate_supplier_id);
		Object[] arguments2 = new Object[] { map2 };
		JSONObject cutterEstimate = JSONObject.parseObject( HproseClinetService.synCall(APIConstants.SMSI_CUTTERINVENTORYANDYIELDESTIMATE, arguments2,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		List<Map<String,Object>> list = (List<Map<String,Object>>)cutterEstimate.get("data");
		for (Map<String, Object> map : list) {
			int use_num = Convert.convertToInt(map.get("use_num")+"",0);
			int inventory_num = Convert.convertToInt(map.get("inventory_num")+"",0);
			int cutter_num = Convert.convertToInt(map.get("cutter_num")+"",0);
			map.put("clean_num",inventory_num+use_num-cutter_num);
		}
		HSSFWorkbook wb = DownExcel.downExcel("刀具库存及预估产能统计表 ", "供应商简称:物料编号:物料简称:物料全称:项目名称:工序名称:领用数量:已排配数量:现有库存:净库存:对应产能", 
        		"supp_name:customer_specs_no:simple_specs_cust:long_specs_cust:project_name:process_name:use_num:cutter_num:inventory_num:clean_num:cutter_life", list);
        // 生成文件名
        String fileName = "CutterEstimateYield" + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") +	 ".xls";
        try {
            response.setContentTypeIfNotSet("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "GB2312"));
            OutputStream out = response.out;
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            list.clear();
        }
	}
	/**
	 * 获取供应商消耗量
	 * @Title: getSuppConsumeSum
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param: @param customer_id
	 * @param: @param dateType
	 * @return: void
	 * @throws
	 * @author caofan
	 * @Date 2015年12月9日 下午5:07:21
	 */
	public static void getSuppConsumeSum() {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id", UserBis.currUser());
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		String res = HproseClinetService.synCall(
				APIConstants.SMSI_GETSUPPCONSUMESUM, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject json = JSONObject.parseObject(res);
		renderJSON(json);
	}

	/**
	 * 获取平均寿命图标
	 * 
	 * @Title: getCutterAvgLife
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param: @param dateType
	 * @param: @param project_id
	 * @param: @param process_id
	 * @param: @param cutter_specs
	 * @return: void
	 * @throws
	 * @author caofan
	 * @Date 2015年12月11日 上午11:54:56
	 */
	public static void getCutterAvgLife(String dateType, String project_id,
			String process_id, String cutter_specs) {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id", "MS_C0000001");
		map.put("project_id", "MS_P0000001");
		map.put("process_id", "MS_R0000001");
		map.put("cutter_specs","D6*r0.5粗"); 
		String res = HproseClinetService.synCall(
				APIConstants.SMSI_GETCUTTERAVGLIFE, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	/**
	 * 获取供应商刀具消耗量
	 * 
	 * @Title: getCutterAvgLife
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param: @param dateType
	 * @param: @param project_id
	 * @param: @param process_id
	 * @param: @param cutter_specs
	 * @return: void
	 * @throws
	 * @author caofan
	 * @Date 2015年12月11日 上午11:54:56
	 */
	public static void getCutterConsumeList(String dateType,String cutter_specs) {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id",UserBis.currUser());
		map.put("cutter_specs",cutter_specs); 
		String res = HproseClinetService.synCall(APIConstants.SMSI_GETCUTTERCONSUMELIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	
	/**
	 * 获取库存图表
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param: @param dateType
	 * @param: @param project_id
	 * @param: @param process_id
	 * @param: @param cutter_specs
	 * @return: void
	 * @throws
	 * @author caofangetOperatorSkillList
	 * @Date 2015年12月11日 上午11:54:56
	 */
	public static void getCutterInventoryList(String dateType,String cutter_specs) {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id",UserBis.currUser());
		map.put("cutter_specs",cutter_specs); 
		String res = HproseClinetService.synCall(APIConstants.SMSI_GETCUTTERINVENTORYLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	
	/**
	 * 操作员技术分析
	* @Title: getOperatorComsumeList 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param material_id    设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void getOperatorComsumeList(String material_id){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id",UserBis.currUser());
		map.put("material_id",material_id); 
		String res = HproseClinetService.synCall(APIConstants.SMSI_GETOPERATORSKILLLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	/**
	 * 领用图表
	 * @Title:        useRecordMonthStatistics 
	 * @Description:  TODO(这里用一句话描述这个方法的作用) 
	 * @param:        @param material_id    
	 * @return:       void    
	 * @throws 
	 * @author        caofan
	 * @Date          2015年12月21日 下午5:30:36
	 */
	public static void useRecordMonthStatistics(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id",UserBis.currUser());
		map.put("material_id",params.get("material_id")); 
		map.put("start_date",params.get("start_date")); 
		map.put("end_date",params.get("end_date")); 
		String res = HproseClinetService.synCall(APIConstants.SMSI_USERECORDMONTHSTATISTICS, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	/**
	 * 回收图表
	 * @Title:        recoveRecordMonthStatistics 
	 * @Description:  TODO(这里用一句话描述这个方法的作用) 
	 * @param:        @param material_id    
	 * @return:       void    
	 * @throws 
	 * @author        caofan
	 * @Date          2015年12月21日 下午5:30:24
	 */
	public static void recoveRecordMonthStatistics(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id",UserBis.currUser());
		map.put("material_id",params.get("material_id")); 
		map.put("start_date",params.get("start_date")); 
		map.put("end_date",params.get("end_date")); 
		String res = HproseClinetService.synCall(APIConstants.SMSI_RECOVERECORDMONTHSTATISTICS, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	
	
	/**
	 * 根据时间段获取项目实际用刀量
	 * @Title:        recoveRecordMonthStatistics 
	 * @Description:  TODO(这里用一句话描述这个方法的作用) 
	 * @param:        @param material_id    
	 * @return:       void    
	 * @throws 
	 * @author        caofan
	 * @Date          2015年12月21日 下午5:30:24
	 */
	public static void projectRealUseStatistics(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("project_id", params.get("project_id"));
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		String res = HproseClinetService.synCall(APIConstants.SMSI_PROJECTREALUSESTATISTICS, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	
	/**
	 * 工序查询用刀量
	 */
	public static void processStatistics(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("process_id", params.get("process_id"));
		map.put("type", params.get("type"));
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		String res = HproseClinetService.synCall(APIConstants.SMSI_PROCESSSTATISTICS, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	/**
	 * 計劃產能
	 */
	public static void productionPlanYield(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("plan_id", params.get("plan_id"));
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		String res = HproseClinetService.synCall(APIConstants.SMSI_PRODUCTIONPLANYIELDSTATISTICS, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	public static void getProjectCutterCostRecord(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id","MS_C0000015");
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		map.put("type","2");
		map.put("project_id","MS_P0000330");
		String res = HproseClinetService.synCall(
				APIConstants.CSTATMI_GETCUTTERUSESTATISTCS, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject json = JSONObject.parseObject(res);
		List<Map<String, Object>> list = (List<Map<String, Object>>) json
				.get("data");
		List<Map<String, Object>> listData = new ArrayList<Map<String, Object>>();
		// 时间列表
		List dateList = new ArrayList();
		// 规格列表
		List materialIdList = new ArrayList();
		StringBuffer dateHead = new StringBuffer();
		StringBuffer dateHeadData = new StringBuffer();
		dateHead.append("项目刀具:单价");
		dateHeadData.append("simple_specs_cust:price");
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map2 = list.get(i);
			// 不包含该时间 添加
			if (!dateList.contains(map2.get("date"))) {
				dateList.add(map2.get("date"));
			}
			// 不包含该规格 添加
			if (!materialIdList.contains(map2.get("material_id"))) {
				materialIdList.add(map2.get("material_id"));
			}
		}
		Map<String, Object> process = new HashMap<String, Object>();
		Map<String, Object> project = new HashMap<String, Object>();
		for (int i = 0; i < list.size(); i++) {
			process.put(list.get(i).get("process_id").toString(), list.get(i).get("process_name"));
			project.put(list.get(i).get("process_id").toString(),  list.get(i).get("project_name"));
		}
		Collections.sort(materialIdList);
		Collections.sort(dateList);
		for (int j = 0; j < dateList.size(); j++) {
			String date = (String) dateList.get(j);
			dateHead.append(":" + date);
			dateHeadData.append(":num" + j);
		}
		dateHead.append(":总量");
		dateHeadData.append(":total");
		for (int i = 0; i < materialIdList.size(); i++) {
		String materialIds = materialIdList.get(i).toString();
		Map<String, Object> map3 = new HashMap<String, Object>();
		map3.put("materialId", materialIds);
		// 获取刀具编码
		for (int k = 0; k < list.size(); k++) {
			Map<String, Object> map2 = list.get(k);
			if (materialIds.equals(map2.get("material_id"))) {
				map3.put("simple_specs_cust", map2.get("simple_specs_cust"));
				break;
			}
		}
		long total  = 0;
		// 循环时间
		for (int j = 0; j < dateList.size(); j++) {
			String date = (String) dateList.get(j);
			// 获取数量
			for (int x = 0; x < list.size(); x++) {
				Map<String, Object> map2 = list.get(x);
				if (date.equals(map2.get("date"))&& materialIds.equals(map2.get("material_id"))) 
				{
					map3.put("num" + j,Integer.parseInt(map2.get("num").toString()));
					total+=Integer.parseInt(map2.get("num").toString());
					break;
				}
				if (x == list.size() - 1) {
					map3.put("num" + j, "");
				}
			}
		}
		map3.put("total", total);
		map3.put("price", 1);
		// 添加 实际领用
		listData.add(map3);
	}
		String title = "";
		for (String keys : project.keySet()) {
			title+=project.get(keys);
			title+="(";
			for (String process_keys : process.keySet()) {
				title+=process.get(process_keys)+",";
			}
			title.substring(0,title.length()-1);
			title+=")  ";
		}
		title+= params.get("start_date")+" ~ "+params.get("end_date");
		
		HSSFWorkbook wb = DownExcel.downExcel(title,dateHead.toString(), dateHeadData.toString(), listData);
		
		String[] headName = dateHead.toString().split("\\:");
		HSSFSheet sheet = wb.getSheetAt(0);
		HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1);
		HSSFCell cell = row1.createCell(0);
		cell.setCellValue("工程核定成本");
		HSSFCellStyle cellStyle = wb.createCellStyle();
		for (int i = 1; i < headName.length; i++) {
		HSSFCell cell2 = row1.createCell(i);
		cell2.setCellValue("");
		}
		String fileName = "CutterUseRecord"	
				+ DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + ".xls";
		try {
			response.setContentTypeIfNotSet("application/vnd.ms-excel");
			response.setHeader("content-disposition", "attachment;filename="
					+ URLEncoder.encode(fileName, "GB2312"));
			OutputStream out = response.out;
			wb.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			list.clear();
			listData.clear();
		}
	}	
	
}
